package cn.lcfms.app.weixin.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import cn.lcfms.bin.Notice;
import cn.lcfms.bin.core.Application;
import cn.lcfms.bin.service.BaseService;
import cn.lcfms.utils.HttpUtils;
import cn.lcfms.utils.TimeUtils;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class WxApiService {
	private static Logger logger = Logger.getLogger(BaseService.class); 
	private static HashMap<String, String> config;
	private static String access_token;
	private static long access_token_get_time=0;//上次获取access_token的时间
	/**
	 * 获取微信配置
	 * @return
	 */
	public HashMap<String, String> getWeixinConfig(){
		if(null==config) {
			freshConfig();
		}
		return config;
	}
	/**
	 * 返回appid
	 * @return
	 */
	public String getAppid() {
		if(null==config) {
			freshConfig();
		}
		return config.get("appid");
	}
	/**
	 * 返回token
	 * @return
	 */
	public String getToken() {
		if(null==config) {
			freshConfig();
		}
		return config.get("token");
	}
	/**
	 * 返回EncodingAESKey
	 * @return
	 */
	public String getEncodingAESKey() {
		if(null==config) {
			freshConfig();
		}
		return config.get("EncodingAESKey");
	}
	/**
	 * 返回AppSecret
	 * @return
	 */
	public String getAppSecret() {
		if(null==config) {
			freshConfig();
		}
		return config.get("AppSecret");
	}
	
	/**
	 * 更新微信配置
	 */
	public void freshConfig() {
		BaseService service = Application.getService("weixin");
		service.order("id");
		service.column("name","value");
		List<HashMap<String, Object>> list = service.selectList();
		config=new HashMap<>();
		list.forEach((HashMap<String, Object> map)->{
			config.put((String)map.get("name"), (String)map.get("value"));
		});
	}
	
	/**
	 * 获取access_token
	 * @throws Exception
	 */
	public String getAccess_token(){
		//调试模式下返回
		boolean debug=(boolean) Application.config("debug.on");
		if(debug) {
			if(null==config) {
				freshConfig();
			}
			return (String) config.get("access_token");
		}
		long time=new Date().getTime()/1000;
		if(WxApiService.access_token==null || WxApiService.access_token_get_time+7200<time){
			String appid=getAppid();
			String AppSecret=getAppSecret();
			String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+AppSecret;
			try {
				String rs = HttpUtils.getdata(url);
				logger.info("从微信获取："+rs);
				JSONObject object=JSONObject.fromObject(rs);
				if(object.has("errcode") && object.getInt("errcode")!=0) {
					logger.error(object.getString("errmsg"));
				}else {
					WxApiService.access_token=object.getString("access_token");			
					WxApiService.access_token_get_time=time;
				}			
			} catch (Exception e) {
				e.printStackTrace();
			}			
		}	
		return WxApiService.access_token;
	}
	/**
	 * 获取自定义菜单
	 */
	public String getMenu() {
		String url="https://api.weixin.qq.com/cgi-bin/menu/get?access_token="+getAccess_token();
		String rs="";
		try {
			rs = HttpUtils.getdata(url);
			logger.info("从微信获取："+rs);
			JSONObject object=JSONObject.fromObject(rs);
			if(object.has("errcode") && object.getInt("errcode")!=0) {
				logger.error(object.getString("errmsg"));
				return "";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rs;
	}
	
	/**
	 * 创建自定义菜单
	 */
	public Notice setMenu(JSON menu) {
		String url="https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+getAccess_token();
		Notice notice=new Notice(1,"创建菜单成功！");
		try {
			String rs = HttpUtils.postJson(menu, url);
			logger.info("从微信获取："+rs);
			JSONObject object=JSONObject.fromObject(rs);
			if(object.has("errcode") && object.getInt("errcode")!=0) {
				logger.error(object.getString("errmsg"));
				notice.setMsg(object.getString("errmsg"));
				notice.setCode(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
			notice.setMsg("系统错误！");
			notice.setCode(0);
		}
		return notice;
	}
	/**
	 * 删除自定义菜单
	 */
	public Notice deleteMenu() {
		String url="https://api.weixin.qq.com/cgi-bin/menu/delete?access_token="+getAccess_token();
		Notice notice=new Notice(1,"删除菜单成功！");
		try {
			String rs = HttpUtils.getdata(url);
			logger.info("从微信获取："+rs);
			JSONObject object=JSONObject.fromObject(rs);
			if(object.has("errcode") && object.getInt("errcode")!=0) {
				logger.error(object.getString("errmsg"));
				notice.setMsg(object.getString("errmsg"));
				notice.setCode(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
			notice.setMsg("系统错误！");
			notice.setCode(0);
		}
		return notice;
	}
	/**
	 * 获取素材总数
	 * @param type 
	 * all 所有
	 * voice_count	语音总数量
	 * video_count	视频总数量
	 * image_count	图片总数量
	 * news_count	图文总数量
	 * @return
	 */
	public int getMaterialCount(String type) {
		String url="https://api.weixin.qq.com/cgi-bin/material/get_materialcount?access_token="+getAccess_token();
		int count=0;
		try {
			String rs = HttpUtils.getdata(url);
			logger.info("从微信获取："+rs);
			JSONObject object=JSONObject.fromObject(rs);
			if(object.has("errcode") && object.getInt("errcode")!=0) {
				logger.error(object.getString("errmsg"));				 
			}else {
				if(type.equals("all")) {
					count=object.getInt("voice_count")+object.getInt("video_count")+object.getInt("image_count")+object.getInt("news_count");
				}else {
					return object.getInt(type);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return count;
	}
	/**
	 *  获取图文素材列表
	 * @param offset 偏移量，从第几个开始取
	 * @param count  取数量
	 * @return
	 */
	public List<HashMap<String, Object>> getMaterialNewsList(int offset,int count) {
		String url="https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token="+getAccess_token();
		JSONObject json=new JSONObject();
		json.put("type", "news");
		json.put("offset", offset);
		json.put("count", count);
		List<HashMap<String, Object>> list=new ArrayList<>();
		try {
			String rs = HttpUtils.postJson(json, url);
			logger.info("从微信获取："+rs);
			JSONObject object=JSONObject.fromObject(rs);
			if(object.has("errcode") && object.getInt("errcode")!=0) {
				logger.error(object.getString("errmsg"));				 
			}else {
				int total=object.getInt("total_count");
				JSONArray jsonArray = object.getJSONArray("item");
				for(int i=0;i<jsonArray.size();i++) {
					JSONObject jsonObject = jsonArray.getJSONObject(i);
					HashMap<String, Object> map=new HashMap<>();
					map.put("count", total);
					map.put("media_id", jsonObject.getString("media_id"));									
					map.put("content",jsonObject.getJSONObject("content").getJSONArray("news_item"));	
					map.put("update_time",TimeUtils.getFormatTime(TimeUtils.Formatter._SHORT, jsonObject.getString("update_time")));	
					list.add(map);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
	/**
	 *  获取视频,图片,语音素材列表
	 * @param offset 偏移量，从第几个开始取
	 * @param count  取数量
	 * @return
	 */
	public List<HashMap<String, Object>> getMaterialElseList(String type,int offset, int count) {
		String url="https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token="+getAccess_token();
		JSONObject json=new JSONObject();
		json.put("type", type);
		json.put("offset", offset);
		json.put("count", count);
		List<HashMap<String, Object>> list=new ArrayList<>();
		try {
			String rs = HttpUtils.postJson(json, url);
			logger.info("从微信获取："+rs);
			JSONObject object=JSONObject.fromObject(rs);
			if(object.has("errcode") && object.getInt("errcode")!=0) {
				logger.error(object.getString("errmsg"));				 
			}else {
				int total=object.getInt("total_count");
				JSONArray jsonArray = object.getJSONArray("item");
				for(int i=0;i<jsonArray.size();i++) {
					JSONObject jsonObject = jsonArray.getJSONObject(i);
					HashMap<String, Object> map=new HashMap<>();
					map.put("count", total);
					map.put("media_id", jsonObject.getString("media_id"));									
					map.put("name",jsonObject.getString("name"));	
					map.put("update_time",TimeUtils.getFormatTime(TimeUtils.Formatter._SHORT, jsonObject.getString("update_time")));	
					map.put("url",jsonObject.getString("url"));	
					list.add(map);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
	/*
	 * 删除永久素材
	 */
	public Notice delMaterial(String media_id) {
		String url="https://api.weixin.qq.com/cgi-bin/material/del_material?access_token="+getAccess_token();
		Notice notice=new Notice(1,"删除素材成功！");
		try {
			JSONObject mo=new JSONObject();
			mo.put("media_id", media_id);
			String rs = HttpUtils.postJson(mo,url);
			logger.info("从微信获取："+rs);
			JSONObject object=JSONObject.fromObject(rs);
			if(object.has("errcode") && object.getInt("errcode")!=0) {
				logger.error(object.getString("errmsg"));	
				notice.setMsg(object.getString("errmsg"));
				notice.setCode(0);
			}
		} catch (Exception e) {
			notice.setMsg("系统错误！");
			notice.setCode(0);
			e.printStackTrace();
		}
		return notice;
	}
}
